package com.yilin.tms.message.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.reflect.TypeToken;
import com.yilin.commons.encrypt.EncryptUtils;
import com.yilin.commons.exception.BusinessException;
import com.yilin.commons.util.HttpService;
import com.yilin.commons.util.JsonUtil;
import com.yilin.tms.core.application.AppUtil;
import com.yilin.tms.core.application.ReturnData;
import com.yilin.tms.core.commons.utils.ParamUtil;
import com.yilin.tms.core.commons.utils.SMSUtil;
import com.yilin.tms.core.commons.annotation.Explain;
import com.yilin.tms.core.entity.message.SmsRecord;
import com.yilin.tms.core.entity.user.account.Account;
import com.yilin.tms.core.entity.user.hatch.HatchPlatProduct;
import com.yilin.tms.core.entity.user.hatch.HatchSms;
import com.yilin.tms.core.remote.IUserRemote;
import com.yilin.tms.message.mapper.SmsRecordMapper;
import com.yilin.tms.message.service.ISmsService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.transaction.Transactional;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 短信服务
 *
 * @author zhangjinyuan
 * @date 2022/10/26
 */
@Service
@Transactional
public class SmsService extends ServiceImpl<SmsRecordMapper, SmsRecord> implements ISmsService {

    private final Logger logger = LoggerFactory.getLogger(SmsService.class);

    @Value("${ylwl-sms.send-account}")
    private String sendAccount;
    @Value("${ylwl-sms.send-password}")
    private String sendPassword;
    @Value("${ylwl-sms.send-url}")
    private String sendUrl;

    @Resource
    SmsRecordMapper smsRecordMapper;
    @Resource
    IUserRemote userRemote;

    private Map<String,HatchPlatProduct> _hatchProductMap = new HashMap<>();
    private Map<String,HatchSms> _hatchSmsMap = new HashMap<>();

    public HatchPlatProduct getHatchProduct(String platId, String productCode) {
        if (_hatchProductMap.get(platId)!=null && _hatchProductMap.get(platId).getProductCode()!=null) return _hatchProductMap.get(platId);
        if (_hatchProductMap.get(productCode)!=null && _hatchProductMap.get(productCode).getProductCode()!=null) return _hatchProductMap.get(productCode);
        if (platId != null){
            _hatchProductMap.put(platId, ParamUtil.isSuccess(userRemote.getPlatProductHatch(platId)));
            return _hatchProductMap.get(platId);
        } else {
            _hatchProductMap.put(productCode,ParamUtil.isSuccess(userRemote.getPlatProductHatchByCode(productCode)));
            return _hatchProductMap.get(productCode);
        }
    }

    public HatchSms getHatchSms(String platId) {
        if (_hatchSmsMap.get(platId)!=null && _hatchSmsMap.get(platId).getSendAccount()!=null) return _hatchSmsMap.get(platId);
        if (platId != null) _hatchSmsMap.put(platId,ParamUtil.isSuccess(userRemote.getSmsHatch(platId)));
        return _hatchSmsMap.get(platId);
    }

    /**
     * 根据日期删除消息记录(真实)
     */
    @Override
    public void deleteByDate(String startDate, String endDate) {
        smsRecordMapper.deleteByDate(startDate, endDate);
    }

    /**
     * 发送短信验证码
     */
    @Override
    public ReturnData<Map<String, Object>> sendCodeMessage(String platId, String productCode, String phone, @Explain("验证码类型") SMSUtil.MsgType msgType) {
        Map<String, Object> map = SMSUtil.canSendCodeNew(phone, msgType);
        Boolean success = (Boolean) map.get(SMSUtil.SUCCESS);
        if (!success) {
            Long surplusSecond = (Long) map.get(SMSUtil.SURPLUS_SECOND);
            String msg = String.format("获取验证码失败，请%d秒后重试", surplusSecond);
            return ReturnData.from(false, msg, map);
        }
        String code = AppUtil.random(6);
        String message;
        if (msgType == SMSUtil.MsgType.phoneCode) {
            message = "您的手机验证码是：" + code + ",请不要把验证码泄露给其他人。";
        } else if (msgType == SMSUtil.MsgType.bindBankcard) {
            message = "您正在添加银行卡，验证码是：" + code + ",请不要把验证码泄露给其他人。";
        } else if (msgType == SMSUtil.MsgType.phoneLogin) {
            message = "您的登录验证码是：" + code + "，请在10分钟内完成登录，请不要把验证码泄露给其他人。";
        } else if (msgType == SMSUtil.MsgType.updatePassword) {
            message = "您正在修改登陆密码，验证码是：" + code + "，请不要把验证码泄露给其他人。";
        } else if (msgType == SMSUtil.MsgType.updateSafePassword) {
            message = "您正在修改安全密码，验证码是：" + code + "，请不要把验证码泄露给其他人。";
        } else if (msgType == SMSUtil.MsgType.organizeRegister) {
            message = "您的注册验证码是：" + code + "，请在10分钟内完成注册，请不要把验证码泄露给其他人。";
        } else if (msgType == SMSUtil.MsgType.employeeRegister) {
            message = "您的管理员正在为你创建账户，验证码：" + code + "，请核实管理员信息后向其提供此验证码，请不要把验证码泄露给其他人。";
        } else {
            return ReturnData.from(false, "参数错误，您不能发送此验证码");
        }
        saveSendMessage(platId, productCode, phone, message, null, msgType, code);
        //保存验证码到磁盘缓存-默认10分钟
        map = SMSUtil.saveCashCode(phone, code, msgType);
        return ReturnData.from(true, "短信验证码发送成功", map);
    }

    /**
     * 发送短信
     */
    @Override
    public void saveSendMessage(String platId, String productCode, String phone, String msg, String confirmNo, SMSUtil.MsgType msgType, String code) {
        try {
            Map<String, Object> param = new HashMap<>();
//            String sendAccount,sendPassword,sendUrl;
            SmsRecord smsRecord = new SmsRecord();
//            if (platId==null && productCode==null){
//                sendAccount = this.sendAccount;
//                sendPassword = this.sendPassword;
//                sendUrl = this.sendUrl;
//                Account success = ParamUtil.isSuccess(userRemote.getSystemYilinUser());
//                smsRecord.setPlatId(success.getSuperiorPlatId());
//                smsRecord.setPlatName(success.getSuperiorPlatName());
//            }else{
//                HatchPlatProduct hatchProduct = getHatchProduct(platId, productCode);
//                HatchSms hatchSms = getHatchSms(hatchProduct.getPlatId());
//                if (hatchSms==null || hatchSms.getSendAccount()==null) throw new BusinessException("SMS孵化配置未填写！");
//                smsRecord.setPlatId(hatchSms.getPlatId());
//                smsRecord.setPlatName(hatchSms.getPlatName());
//                sendAccount = hatchSms.getSendAccount();
//                sendPassword = hatchSms.getSendPassword();
//                sendUrl = hatchSms.getSendUrl();
//            }
            param.put("account", sendAccount);
            param.put("password", sendPassword);
            param.put("msg", msg);
            param.put("phone", phone);
            String paramJson = JsonUtil.objectToJson(param);
            String ret = HttpService.httpPostWithJson(sendUrl, paramJson);
            Map<String, Object> result = JsonUtil.jsonToObject(ret, new TypeToken<Map<String, Object>>() {});
            smsRecord.setContent(msg);
            smsRecord.setCreateTime(new Date());
            smsRecord.setPhone(phone);
            smsRecord.setConfirmNo(confirmNo);
            smsRecord.setMsgType(msgType);
            smsRecord.setCode(code);
            smsRecord.setSendPoint(null);
            if ("0".equals(result.get("code"))) {
                smsRecord.setStatus(SmsRecord.Status.success);
            } else {
                smsRecord.setStatus(SmsRecord.Status.fail);
            }
            smsRecordMapper.insert(smsRecord);
        } catch (IOException e) {
            logger.info("创蓝接口连接失败！！！");
        }
    }

//    public static void main(String[] args) {
//        String time=String.valueOf(new Date().getTime()).substring(0,10);
//        Map<String, Object> param = new HashMap<>();
//        param.put("username", "18984931688");
//        param.put("timestamp", time);
//        param.put("signature", AppUtil.md5("18984931688"+"time"+""));
//        param.put("appid", "153");
//        param.put("signature_scene_typ", "1");
//        param.put("signature_name", "极舜货运");
//        String paramJson = JsonUtil.objectToJson(param);
//        String ret = HttpService.httpPostWithJson("https://api.chuanglan.com/api/apis/signature/signatureAdd", paramJson);
//    }

}
